/**
 * Created on 20/04/2008
 * 
 */
package com.apbetioli.mapr.place.dao;

import com.apbetioli.mapr.place.entity.Place;
import com.apbetioli.mapr.util.properties.PropertiesLoaderImpl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 *
 * @author Alexandre Parra Betioli
 */
class PlacesDaoNoTransaction implements PlacesDaoInterface {

    private EntityManagerFactory emf;
    private EntityManager em;
    
    public PlacesDaoNoTransaction() {
        em = this.getEntityManager();
    }
    
    private EntityManager getEntityManager() {
        if( emf == null )
            emf = Persistence.createEntityManagerFactory( PropertiesLoaderImpl.getValue("config.properties", "persistence.unit") );
        
        return emf.createEntityManager();
    }
    
    public EntityTransaction getTransaction() {
        return em.getTransaction();
    }    
    
    public Place save( final Place place ) {
        
        if(place == null)
            throw new NullPointerException("Place is null");
        
        Place old = findByName(place.getName());
        
        em.merge( place );
        
        return old;
    }
    
    public Place delete( final String name ) {
        
        Place old = findByName( name );
    
        if(old != null)
            em.remove( em.merge(old) );
        
        return old;
    }

    public Place findByName( final String name ) {
        
        if(name == null)
            return null;
        
        Place p = em.find(Place.class, name);
        
        if( p != null )
            return p.clone();
        else 
            return null;
    }
    
    public List<Place> listAll() {
        return em.createNamedQuery("Place.listAll").getResultList();
    }
}
